package com.ktgj.customer.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ktgj.common.core.text.UUID;
import com.ktgj.common.core.utils.HttpClientUtil;
import com.ktgj.common.core.utils.RSAUtils;
import com.ktgj.common.core.utils.StringUtils;
import com.ktgj.customer.domain.Insurance.Applicantinfo;
import com.ktgj.customer.domain.Insurance.ApplyPolicyNoPayInput;
import com.ktgj.customer.domain.Insurance.ApplyPolicyNoPayOutput;
import com.ktgj.customer.domain.Insurance.Datum;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.protocol.HTTP;
import org.springframework.stereotype.Component;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class PaInsuranceUtils {
    //平安正式信息
    /*private String ApiUrl = "https://api.pingan.com.cn/open/appsvr/property/";

    private String clientId = "P_PINGAN_JSJ_XIANGKA";
    private String clientSecret = "m7H1wz4n";

    private String partnerName = "P_JSSJ_PE";
    private String departmentCode = "2320168";
    private String TokenUrl = "https://api.pingan.com.cn/oauth/oauth2/access_token?client_id={0}&grant_type=client_credentials&client_secret={1}";*/


    //平安测试信息
    private String ApiUrl = "https://test-api.pingan.com.cn:20443/open/appsvr/property/";

    private String clientId = "P_PINGAN_JSJ_XIANGKA";
    private String clientSecret = "dM53Q7nn";

    private String partnerName = "P_JSSJ_PE";
    private String departmentCode = "2320168";
    private String TokenUrl = "https://test-api.pingan.com.cn:20443/oauth/oauth2/access_token?client_id={0}&grant_type=client_credentials&client_secret={1}";

    /// <summary>
    /// 获取token
    /// </summary>
    /// <param name="nType">1仅从缓存中获取token，2重新获取token并将token放入缓存中</param>
    /// <returns></returns>
    public String _GetToken() {
        String strTokenUrl = TokenUrl.replaceAll("\\{0}", clientId);
        strTokenUrl = strTokenUrl.replaceAll("\\{1}", clientSecret);
        String strTokenJson = HttpClientUtil.doGet(strTokenUrl);//获取token
        System.out.println(strTokenJson);
        Token tk = JSONObject.parseObject(strTokenJson, Token.class);
        return tk.data.access_token;

    }


    /// <summary>
    /// 平安开保接口发起请求
    /// </summary>
    /// <param name="strJson">请求参数</param>
    /// <param name="strApiName">请求接口名</param>
    /// <returns></returns>
    private String _PostApi(String strJson, String strApiName) {
        String strRtn = "";
        try {
            String strRequest_id = strApiName + new Date().getTime();

            String strToken = "";
            for (int i = 0; i < 5; i++) {
                strToken = _GetToken();
                if (!StringUtils.isEmpty(strToken)) break;
            }

            String strUrl = ApiUrl + strApiName + "?access_token=" + strToken + "&request_id=" + strRequest_id;

            HashMap<String,String> mHeader = new HashMap<>();
            mHeader.put("Content-Type","application/json;charset=utf-8");
            mHeader.put("Accept","application/json;charset=utf-8");
            strRtn = HttpClientUtil.doPostJsonWithHeaderMap(strUrl, strJson,mHeader);
//            strRtn = HttpClientUtil.doPostJson(strUrl, strJson);

            //如果token过期，则重新获取token
            if (strRtn.indexOf("access_token为空") >= 0 || strRtn.indexOf("已失效的access_token") >= 0) {
                _GetToken();
            }
        } catch (Exception ex) {
            strRtn = "发送报文时系统异常:" + ex.getStackTrace() + ex.getMessage();
        }
        return strRtn;

    }

    /// <summary>
    /// 平安开保接口
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public ApplyPolicyNoPayOutput ApplyPolicyNoPay(ApplyPolicyNoPayInput input) {
        ApplyPolicyNoPayOutput output = new ApplyPolicyNoPayOutput();

        try {
            input.partnerName = partnerName;
            input.departmentCode = departmentCode;

            String strApiName = "asyncApplyPolicyNoPay";

            String strRtn = _PostApi(JSON.toJSONString(input), strApiName);

            if (StringUtils.isEmpty(strRtn)) {
                output.msg = "调用接口无响应";
                output.ret = "-1";
                return output;
            }
            if (strRtn.indexOf("系统异常") >= 0) {
                output.msg = strRtn;
                output.ret = "-2";
                return output;
            }

            output = JSONObject.parseObject(strRtn, ApplyPolicyNoPayOutput.class);
        } catch (Exception ex) {
            output.msg = "解析数据时系统异常:" + ex.getStackTrace() + ex.getMessage();
            output.ret = "-1";

        } finally {
            //systemfile.WriteLog("ApplyPolicyNoPay", Newtonsoft.Json.JsonConvert.SerializeObject(input) + "返回参数:" + Newtonsoft.Json.JsonConvert.SerializeObject(output));
        }
        return output;
    }



    public static void main(String[] args) {
        Applicantinfo applicantinfo = new Applicantinfo();
        applicantinfo.name = "李博洋";//姓名
        applicantinfo.certificateType = "01";//证件类型,01:身份证、02：护照、03：军人证、04：港澳通行证，05：驾驶证、06：港澳回乡证或台胞证，07：临时身份证
        applicantinfo.certificateNo = "231182200010260536";//证件号码
        applicantinfo.mobileTelephone = "18745654672";//用户手机号码
        applicantinfo.age = "22";//年龄
        applicantinfo.birthday = "2000-10-26";//出生年月 Date 非身份证时必填
        applicantinfo.sexCode = "M";//性别F,M 非身份证时必填
        ApplyPolicyNoPayInput applyPolicyNoPayInput = new ApplyPolicyNoPayInput();
        applyPolicyNoPayInput.applicantInfo = applicantinfo;
        PaInsuranceUtils paInsuranceUtils = new PaInsuranceUtils();
//        String getToken = paInsuranceUtils._GetToken();
        paInsuranceUtils.ApplyPolicyNoPay(applyPolicyNoPayInput);
    }


    public static class AuisInsuranceDataResponse {
        public AuisInsuranceDataResponse() {
            this.PolicyInfo = new AuisInsuranceDataResponsePolicyInfo();
        }

        public String ReturnCode;
        public String ReturnMessage;
        public String SerialNumber;
        public AuisInsuranceDataResponsePolicyInfo PolicyInfo;
    }

    public static class AuisInsuranceDataResponsePolicyInfo {
        public String PolicyNo;
        public String Code;
        public String Message;
    }


    static class Token {
        public String ret;
        public PaData data;
        public String msg;

    }

    static class PaData {
        public String expires_in;
        public String openid;
        public String access_token;
    }
}
